/* Copyright 2014 Jan Wolter */
#include "stack.h"
#include "tableau.h"
#include "found.h"
#include "bouquet.h"
#include "solve.h"
#include "game.h"

char *gamename= "Three Blind Mice";
char *gameopt= "AW";
Stack *gathered= NULL;
Stack *temp= NULL;

#define SORT

int nplayed= 0;
int nwon= 0;
int cardsleft= 0;
int maxoff;

int kingonly= 1;
int maywrap= 0;
int columns= 10;
int percol= 5;
int hidecol= 3;

void setopt(char c)
{
    switch (c)
    {
	case 'A': kingonly= 0; break;

	case 'W': maywrap= 1; break;
    }
}

/* This is the main program for setting up the current game */
void exec(int gather, int arif, int over, int cut)
{
    /* Could set things like ndeck, nsuit here */

    /* Build and shuffle the deck */
    Stack *shuf= mixcards(arif, over, cut);

    /* Create the foundations
     *   For complete sequences we MUST use the sf_complete handler */
    superfound= sf_complete;
    for (int s= 0; s < nsuit; s++)
	makeFound(1, s, +1, 13);

    /* Create the tableau */
    for (int i= 1; i <= columns; i++)
	makeTableau(percol, i <= hidecol ? FLIP_THREE : FLIP_NONE, shuf,
	    S_SAMESUIT, -1, S_ANYTHING, npip,
	    maywrap ? 0 : 1, kingonly ? F_KINGONLY : F_ANYTHING,
	    BREAK_NOFIT, 0);

    makeBouquet(shuf, 1, 0);

    freeStack(shuf);

    if (verbose > 1) printState(stdout, stacks);

    maxoff= 0;
    int win= solve(gather,0);

    if (verbose > 0) printf("maxoff=%d\n",maxoff);
    nplayed++;
    cardsleft+= maxoff;
    if (win) nwon++;

    cleanFound();
    cleanTableau();
    cleanBouquet();
    cleanStacks();
    cleanVisited();
}

void gatherAll()
{
    if (gathered == NULL)
	gathered= allocStack(ncard);
    else
	gathered->n= 0;

    gatherFound(gathered);
    gatherTableau(gathered);
    gatherBouquet(gathered);
    if (gathered->n != ncard)
    {
	printf("Gather Failed - found %d cards\n",gathered->n);
	exit(1);
    }
}

/* How good is a move? Returns 0 if the move is completely safe and should
 * be made immediately without counting this position a a choice point for
 * backtracking. Positive values are lower for better moves. Negative values
 * mean the move should not be done at all.
 */
int rateMove(Stack *src, int index1, int len, Stack *dst)
{
    /* Always safe to move a stack to the foundation in Three Blind Mice */
    if (dst->type == FOUND) return 0;

    /* Not too fond of filling empty spaces if they are fillable by any card */
    if (!kingonly && dst->n == 0) return 20;

    /* Rather fond of creating empty spaces if they are fillable by any card */
    if (!kingonly && index1 == 0) return 1;

    /* Also like turning over new cards */
    if (index1 > 0 && !src->c[index1-1]->faceup) return 2;

    return 3;
}

void printState(FILE *f, Stack *stks)
{
    printFound(f, stks);
    printTableau(f, stks);
    printBouquet(f, stks);
}

int victory()
{
    int off= nOff();
    if (off > maxoff) maxoff= off;
    return (off == ncard);
}

/* Return a quality rating for the current solution. Bigger is better. Usually
 * it's just cards off. This is used to decide which solution to report in
 * cases where we never win.
 */
int quality()
{
    return nOff();
}

#ifdef SORT
/* Comparision function for stack order normalization in currstate() */
static int cmpstacks(const void *p1, const void *p2)
{   
    const Stack *s1= *(const Stack **)p1;
    const Stack *s2= *(const Stack **)p2;
    if (s1->n == 0 || s2->n == 0)
	return s2->n - s1->n;
    int c1= s1->c[0] - deck;
    int c2= s2->c[0] - deck;
    return c2 - c1;
}
#endif

void summary()
{
    printf("Played:    %d games\n",nplayed);
    printf("Won:       %d games (%.2f%)\n",nwon,(float)nwon*100/nplayed);
    printf("Cards Off: %.2f\n",(float)cardsleft/nplayed);
}

/* Return a string that uniquely describes the current state. */
char *currstate()
{
    /* ncards for all the cards on things, 7 for card list terminators
     */
    char buf[ncard+20], *p= buf;

    /* List of cards on each tableau pile.
     * We add 52 to any facedown card.
     */
#ifdef SORT
    /* We normalize the order of the tableau piless, sorting them by the
     * first card on them.
     */
    Stack *norm[12];
    for (int k= 0; k < ntableau; k++)
	norm[k]= stacks + tableau[k].id;
    qsort(norm, ntableau, sizeof(Stack *), cmpstacks);

    for (int k= 0; k < ntableau; k++)
    {
	Stack *s= norm[k];
	for (int i= 0; i < s->n; i++)
	    *(p++)= 1 + (s->c[i] - deck) + (s->c[i]->faceup ? ncard : 0);
	*(p++)= 2*ncard + 1; /* The card list terminator */
    }
#else
    for (int k= 0; k < ntableau; k++)
    {
	Stack *s= stacks + tableau[k].id;
	for (int i= 0; i < s->n; i++)
	    *(p++)= 1 + (s->c[i] - deck) + (s->c[i]->faceup ? ncard : 0);
	*(p++)= 2*ncard + 1; /* The card list terminator */
    }
#endif

    *p= '\0';

    return strdup(buf);
}
